<?php

namespace App\Repositories;
use App\Interfaces\PasswordCouponService;
use App\Models\PasswordCoupon;
use App\Models\Coupon;
use App\Exceptions\Interfaces\PasswordCouponServiceException;
use Auth,Log,DB;
use Illuminate\Database\Eloquent\Collection;

class PasswordCouponRepository implements  PasswordCouponService
{



    /**
     * 创建优惠口令
     * @param  [type] $pwd_num   [要生成的口令数量]
     * @param  [type] $coupon_id [优惠券id]
     * @return [type]            [description]
     */
    public function createPwds($pwd_num, $coupon_id)
    {

        $pwds = [];                     //口令的集合

        if (empty($pwd_num)) {

            throw new PasswordCouponServiceException("要生成的口令数量不能为空");
        }

        if (empty($coupon_id)) {

            throw new PasswordCouponServiceException("对应的优惠券id不能为空");
        }

        $pwds_record = ['coupon_id'=>$coupon_id, 'password_status'=>0, 'created_at'=>date('Y-m-d H:i:s')];                     //口令记录的所有字段的集合,user_id:用户id; coupon_id:优惠券id; password_status:口令的状态,0:未发送,1:已发送,2:已激活;created_at:创建时间;

        // $pwds_record['coupon_id'] = $coupon_id;

        DB::beginTransaction();//开启事务,开始批量操作
        try {

            for ($i=0; $i < $pwd_num; $i++) {

                $pwd_str = $this->getNoRepeatStr();         //生成口令，并且与数据库中已有的不重复

                $pwds_record['password'] = $pwds[$i] = $pwd_str;

                //将生成的所有口令插入到数据库表中
                PasswordCoupon::create($pwds_record);
            }

        }catch (PasswordCouponServiceException $e){

            DB::rollback();

            throw new PasswordCouponServiceException($e->getMessage());
        }

        DB::commit();

        return $pwds;
    }


    /**
     * 使用递归方法获取与数据库中不重复的口令值
     * @param  [type]  $password [口令值]
     * @param  integer $length   [口令长度]
     * @return [type]            [description]
     */
    public function getNoRepeatStr($password = '', $length=0)
    {

        if ($length>0) {

            $pwd_str = getUuid($length);           //获取随机字符串，默认32位，可以带上要获取的字符串的长度，如：getUuid(15)
        }else{

            $pwd_str = getUuid();                  //获取随机字符串，默认32位，可以带上要获取的字符串的长度，如：getUuid(15)
        }


        if ($password) {

            $lrange = PasswordCoupon::find($password);              //获取一条hash记录的所有字段信息

            if ($lrange) {

                $pwd_str = $this->getNoRepeatStr($password);
            }
        }

        return $pwd_str;
    }

    /**
     * 获取指定优惠券的口令
     * @param int $coupon_id      		优惠券id
     * @param int $password_status    	口令状态
     * @return mixed  包含: 1.用户所有的收货地址
     */
    public function getPwds($coupon_id, $password_status = 0){

        return PasswordCoupon::where('coupon_id', $coupon_id)->where('password_status', $password_status)->get();
    }


    /**
     * [更新口令状态]
     * @param  [type]  $password_status [口令状态,0:未发送,1:已发送,2:已激活;]
     * @param  [type]  $send_time       [发送时间]
     * @param  integer $user_id         [用户id]
     * @param  [type]  $use_time        [用户激活时间]
     * @return [type]                   [description]
     */
    public function updatePwds($password, $password_status, $send_time = null, $user_id = 0, $use_time = null){


        $pwds_record = [];              //口令记录的所有字段的集合,user_id:用户id; coupon_id:优惠券id; password_status:口令的状态,0:未发送,1:已发送,2:已激活; create_at:创建时间; use_time:激活时间;

        $password_coupon = PasswordCoupon::find($password);

        if (empty($password_coupon)) {

            /*$return['status'] = 0;

            $return['message'] = '口令['.$password.']不存在';

            return $return;*/

            throw new PasswordCouponServiceException("口令['.$password.']不存在");
        }

        if (empty($password_status)) {

            /*$return['status'] = 0;

            $return['message'] = '口令状态不能为空';

            return $return;*/

            throw new PasswordCouponServiceException("口令状态不能为空");
        }else{

            switch ($password_status) {

                case 1:

                    if ($password_coupon->password_status != 0) {

                        /*$return['status'] = 0;

                        $return['message'] = '只有未发送的口令才可以发送';

                        return $return;*/

                        throw new PasswordCouponServiceException("只有未发送的口令才可以发送");
                    }

                    if (empty($send_time)) {

                        /*$return['status'] = 0;

                        $return['message'] = '发送时间不能为空';

                        return $return;*/

                        throw new PasswordCouponServiceException("发送时间不能为空");
                    }else{

                        $pwds_record['send_time'] = $send_time;
                    }

                    break;

                case 2:

                    if ($password_coupon->password_status != 1) {

                        /*$return['status'] = 0;

                        $return['message'] = '只有已发送的口令才可以激活';

                        return $return;*/

                        throw new PasswordCouponServiceException("只有已发送的口令才可以激活");
                    }

                    if (empty($user_id)) {

                        /*$return['status'] = 0;

                        $return['message'] = '用户id不能为空';

                        return $return;*/

                        throw new PasswordCouponServiceException("用户id不能为空");
                    }else{

                        $pwds_record['user_id'] = $user_id;
                    }

                    if (empty($use_time)) {

                        /*$return['status'] = 0;

                        $return['message'] = '激活时间不能为空';

                        return $return;*/

                        throw new PasswordCouponServiceException("激活时间不能为空");
                    }else{

                        $pwds_record['use_time'] = $use_time;
                    }

                    break;
            }

            $pwds_record['password_status'] = $password_status;
        }

        return $password_coupon->update($pwds_record);
    }



    /**
     * 获取未发送的口令的优惠券列表
     * @return [type]            [description]
     */
    public function getCouponNoSend(){

    	$coupons = [];

    	$coupon_ids  = PasswordCoupon::where('password_status', 0)->groupBy('coupon_id')->lists('coupon_id');

    	$num = 0;

    	foreach ($coupon_ids as $key => $value) {

    		$coupon = Coupon::find($value);

    		if ($coupon) {

    			$coupons[$num] = $coupon->toArray();

    			$num++;
    		}
    	}

    	// $coupon_ids  = PasswordCoupon::select('coupon.*')->where('password_status', 0)->groupBy('password_coupon.coupon_id')->leftJoin('coupon', 'password_coupon.coupon_id', '=', 'coupon.id')->get();

    	return $coupons;
    }


    /**
     * 根据口令id获取口令信息
     * @return [type]            [description]
     */
    public function getCouponByPwd($password){


        return PasswordCoupon::find($password);
    }
}